package org.ruoyi.knowledge.chain.vectorizer;

import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.knowledge.domain.vo.KnowledgeInfoVo;
import org.ruoyi.knowledge.service.IKnowledgeInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Ragflow向量化实现
 * 专门用于Ragflow服务的向量化
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RagflowVectorization implements Vectorization {

    @Lazy
    @Resource
    private IKnowledgeInfoService knowledgeInfoService;

    @Value("${chat.api.host:http://192.168.0.150:7777/api/v1/}")
    private String apiHost;
    
    @Value("${chat.api.key:ragflow-liZDlhNjIwYTViMzExZjBiNTE1MjY1ZW}")
    private String apiKey;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public List<List<Double>> batchVectorization(List<String> chunkList, String kid) {
        try {
            log.info("开始向量化，文本数量: {}, 知识库ID: {}", chunkList.size(), kid);
            
            KnowledgeInfoVo knowledgeInfoVo = knowledgeInfoService.queryById(Long.valueOf(kid));
            if (knowledgeInfoVo == null) {
                throw new RuntimeException("知识库不存在: " + kid);
            }

            // 构建请求 - Ragflow可能没有直接的embeddings API
            // 暂时使用OpenAI兼容的API路径
            String url = apiHost + "/v1/embeddings";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("input", chunkList);
            requestBody.put("model", knowledgeInfoVo.getVectorModel());

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 发送请求
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("API调用失败，状态码: " + response.getStatusCode());
            }

            Map<String, Object> responseBody = response.getBody();
            if (responseBody == null) {
                throw new RuntimeException("API返回数据为空");
            }

            // 解析响应
            log.info("Ragflow API响应: {}", responseBody);
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) responseBody.get("data");
            if (dataList == null || dataList.isEmpty()) {
                log.error("API返回的data字段为空，完整响应: {}", responseBody);
                throw new RuntimeException("API返回的data字段为空");
            }

            List<List<Double>> vectorList = new ArrayList<>();
            for (Map<String, Object> data : dataList) {
                List<Double> embedding = (List<Double>) data.get("embedding");
                if (embedding != null) {
                    vectorList.add(embedding);
                }
            }

            log.info("向量化完成，生成向量数量: {}", vectorList.size());
            return vectorList;

        } catch (Exception e) {
            log.error("向量化失败: {}", e.getMessage(), e);
            throw new RuntimeException("向量化失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<Double> singleVectorization(String chunk, String kid) {
        List<String> chunkList = new ArrayList<>();
        chunkList.add(chunk);
        List<List<Double>> vectorList = batchVectorization(chunkList, kid);
        return vectorList.isEmpty() ? new ArrayList<>() : vectorList.get(0);
    }
}
